<template>
	<div class="sku-dialog point-sku-dialog">
    <van-popup class="sku-pop" v-model="overlayVisible" position="bottom">
      <div
        v-show="showSkuDetail"
        :class="dialogType"
        class="sku-wrapper">
        <div class="sku-wrapper-app">
          <!--头部商品信息-->
          <div class="sku-wrapper-app-head">
            <div class="left-wrap">
              <div class="img">
                <img :src="goodsImg" alt="">
              </div>
            </div>
            <div class="right-wrap">

              <!--弹层的价格 &#45;&#45; 不同的模式不同-->
              <!-- v-if="dialogType == 'default'" -->
              <div class="right-wrap-item price">
                <!--默认的价格-->
                <span class="sku-price" v-if="htmlData.item_detail">
                  <span>{{htmlData.item_detail.points}}{{htmlData.point_name}}</span>
                </span>
              </div>
              <!--弹层的价格 &#45;&#45; 不同的模式不同-->
              <div class="right-wrap-item choose" v-if="hasSku">{{ skuNameStr }}</div>
            </div>
            <div class="close" @click="handleCloseDialog">
              <span class="img-close"></span>
            </div>
          </div>

          <div class="sku-wrapper-app-body">
            <!--sku选择部分 普通-->
            <div >
              <div v-if="skuList && skuList.length > 0">

                <!--普通sku-->
                <div class="sku-item" v-for="(item,index) in skuList" :key="index">
                  <div class="sku-item-title">{{ item.property_name }}</div>
                  <div class="sku-item-app">
                    <van-button
                      v-if="child.sku_name"
                      v-for="(child, num) in item.child_names"
                      :key="num"
                      @click="handleClickSku(child, num, index)"
                      round hairline class="btn"
                      :class="[child.active ? 'active': '', child.isShow ? '':'noneActive']">{{ child.sku_name }}</van-button>
                  </div>
                </div>
              </div>
              <div class="sku-item">
                <div class="sku-item-add">
                  <span class="sku-item-add-title">购买数量</span>

                  <div class="sku-item-add-con">
                    <count-plug v-model="formData.addNum"></count-plug>
                  </div>
                </div>
              </div>
            </div>

            <!--时间 备注内容-->
            <div >
              <div class="sku-item" v-if="htmlData.item_config && htmlData.item_config.shopping_need_date == 1">
                <div class="sku-item-date" @click="handleOpenDatePicker">
                  <span class="sku-item-date-title">{{htmlData.item_config.shopping_date_name}}</span>
                  <div class="sku-item-date-con" >
                    <div class="input">
                      <input v-model="formData.dateTime" readonly @blur="blurEvent" type="text" :placeholder="htmlData.item_config.shopping_date_hint">
                    </div>
                    <time-picker :visible.sync="dateTimeVisible" v-model="formData.dateTime" :minDate="minDate" :maxDate="maxDate"></time-picker>
                  </div>
                </div>
              </div>

              <div class="sku-item" v-if="htmlData.item_config && htmlData.item_config.shopping_need_memo == 1">
                <div class="sku-item-date">
                  <span class="sku-item-date-title">备注</span>
                  <div class="sku-item-date-con" >
                    <div class="input sku-bz-wd">
                      <input v-model="formData.mark" @blur="blurEvent" type="text" :placeholder="htmlData.item_config.shopping_memo_hint">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!--底部按钮信息-->
          <div class="sku-wrapper-app-foot">
            <div class="sku-btn" v-if="activityType == 'addCart'">
              <div @click="handleClickAddCar" class="sku-btn-item pingt-gra-btn">确定</div>
            </div>
            <div class="sku-btn" v-else-if="activityType == 'buyNow'">
              <div @click="handleClickBuyNow" class="sku-btn-item pingt-gra-btn">确定</div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Vue from 'vue'
import Store from '@/utils/store'
import CountPlug from '@/components/CountPlug'
import timePicker from '../timePicker'
import { scaleGoodsPrice } from '@/utils/index'
import { inPointCart } from '@/api/item/item'

export default Vue.extend({
  name: 'index',
  components: {
    CountPlug,
    timePicker
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    visible: {
      type: Boolean,
      default: false
    },
    itemId: {
      type: Number,
      default: 0
    },
    activityType: {
      default: '' // 搭配套餐:collocate
    },
    detailAll: {
      type: Object
    }
  },
  computed: {
  },
  data() {
    return {
      showSkuDetail: false,
      dialogType: 'default',
      skuList: [], // 商品SKU列表
      selectArr: [], // 存放被选中的值
      shopItemInfo: {}, // 存放要和选中的值进行匹配的数据
      subIndex: [], // 是否选中因为不确定是多规格还是单规格，所以这里定义数组来判断
      arrSkuImg: [], // 商品sku图片
      skuInfo: null,
      skuObj: {}, // 选完SKU后的SKU数据
      hasSku: true, // 是否有sku
      skuNameStr: '', // 已选择的文字显示
      dhSkuList: [], // 订货商SKU列表
      noChooseProp: [], // 未选择的sku
      htmlData: '',
      goodsImg: '',
      goodsPrice: '',
      formData: {
        dateTime: '',
        addNum: 1,
        skuKeyStr: '',
        mark: '',
        item_cycle_sku: '',
        item_cycle_delivery: ''
      },
      overlayVisible: false,
      dateTimeVisible: false,
      minDate: '',
      maxDate: ''
    }
  },
  created() {
    if (this.detailAll.item_config && this.detailAll.item_config.shopping_date_start) {
      this.minDate = this.formatDate(this.detailAll.item_config.shopping_date_start)
    }
    if (this.detailAll.item_config && this.detailAll.item_config.shopping_date_end) {
      this.maxDate = this.formatDate(this.detailAll.item_config.shopping_date_end)
    }
  },
  watch: {
    itemId(val) {
      // 改变商品时先清空数据
      this.clearData()
      this.getDetailAjaxFn(val)
    },
    visible(val) {
      this.overlayVisible = val
    },
    overlayVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    initSku() {
      const self = this
      for (const i in self.dhSkuList) {
        self.shopItemInfo[self.dhSkuList[i].sku_name] = self.dhSkuList[i] // 修改数据结构格式，改成键值对的方式，以方便和选中之后的值进行匹配
      }
      self.checkItem(1) // 初始化传1
    },
    specificationBtn(item, n, index) {
      const self = this
      if (self.selectArr[n] != item) {
        self.selectArr[n] = item
        self.subIndex[n] = index
      } else {
        self.selectArr[n] = ''
        self.subIndex[n] = -1 // 去掉选中的颜色
      }
      self.checkItem()
    },
    checkItem(init) {
      // init 是否初始化时
      const self = this
      const option = self.skuList
      const result = [] // 定义数组储存被选中的值
      for (const i in option) {
        if (typeof self.selectArr[i] !== 'function') {
          result[i] = self.selectArr[i] ? self.selectArr[i] : ''
        }
      }
      for (const i in option) {
        const last = result[i] // 把选中的值存放到字符串last去
        for (const k in option[i].child_names) {
          if (typeof option[i].child_names[k].sku_name === 'string') {
            result[i] = option[i].child_names[k].sku_name // 赋值，存在直接覆盖，不存在往里面添加name值
            option[i].child_names[k].isShow = self.isMay(result) // 在数据里面添加字段isShow来判断是否可以选择
            if (option[i].child_names[k].sku_img && (init == 1)) {
              this.arrSkuImg.push(option[i].child_names[k].sku_img)
            }
          }
        }
        result[i] = last // 还原，目的是记录点下去那个值，避免下一次执行循环时被覆盖
      }
      self.$forceUpdate() // 重绘
    },
    isMay(result) {
      for (const i in result) {
        if (result[i] == '') {
          return true // 如果数组里有为空的值，那直接返回true
        }
      }
      const newKey = result.join(' ')
      // // console.log(this.shopItemInfo, 'ssaasdasd', newKey)
      if (this.shopItemInfo[newKey]) {
        /* eslint-disable */
          return this.shopItemInfo[newKey].num == 0 ? false : true // 匹配选中的数据的库存，若不为空返回true反之返回false
        }
      },
      /**
       * 点击SKU
       */
      handleClickSku(item, num, index) {
        const skuList = this.skuList
        const child_names = skuList[index].child_names
        child_names.forEach((sku, number) => {
          if (num == number) {
            if (!sku.active) {
              this.$set(this.skuList[index].child_names[num], 'active', true)
              if (this.skuList[index].child_names[num].sku_img) {
                this.goodsImg = this.skuList[index].child_names[num].sku_img
              }
            } else {
              this.$set(this.skuList[index].child_names[num], 'active', false)
            }
          } else {
            this.$set(this.skuList[index].child_names[number], 'active', false)
          }
        })
        this.dealFindSkuInfo()
        this.specificationBtn(item.sku_name, index, num)
      },
      /**
       * 找出SKU信息
       */
      dealFindSkuInfo() {
        const skuList = this.skuList
        const arrSku = [] // 存储sku的key
        const arrSkuName = [] // 存储sku的文字信息
        skuList.forEach(item => {
          if (Array.isArray(item.child_names)) {
            item.child_names.forEach(sku => {
              if (sku.active) {
                arrSku.push(sku.prop_id)
                arrSkuName.push(sku.sku_name)
              }
            })
          }
        })
        const skuKeyStr = arrSku.join(';')
        const skuInfo = this.skuInfo
        const objKeys = Object.keys(skuInfo)
        if (objKeys.indexOf(skuKeyStr) != -1) {
          this.skuObj = Object.assign(this.skuObj, skuInfo[skuKeyStr], true)
          this.formData.skuKeyStr = skuKeyStr
        }
        // 检索选择的规格
        this.validateSpecAll()
      },
      /**
       * 验证是否选中
       */
      validateSpecAll() {
        const buySpecList = this.buySpecList
        const estimeDeliverList = this.estimeDeliverList
        const buySpecArr = [] // 存储选中的周期购规格
        const estimeDeliverArr = [] // 存储选中的配送时间
        const skuList = this.skuList
        const arrSku = [] // 存储sku的key
        const arrSkuName = [] // 存储sku的文字信息
        const propName = []
        const noChooseProp = []
        skuList.forEach(item => {
          noChooseProp.push(item.property_name)
          if (Array.isArray(item.child_names)) {
            item.child_names.forEach(sku => {
              if (sku.active) {
                arrSku.push(sku.prop_id)
                arrSkuName.push(sku.sku_name)
                propName.push(item.property_name)
              }
            })
          }
        })
        // 周期购有单独的规格
        if (this.htmlData.activity == 7) {
          if (Array.isArray(buySpecList)) {
            this.buySpecStr = ''
            this.formData.item_cycle_sku = ''
            buySpecList.forEach(item => {
              if (item.active) {
                this.buySpecStr = `(${this.htmlData.item_cycle.item_cycle_type},共${item.cycle_key}次)`
                this.formData.item_cycle_sku = item.cycle_key // 周期购规格要提交的数据
                buySpecArr.push(item.sku_describe)
                propName.push('周期购规格')
              }
            })
            if (buySpecList.length > 0) noChooseProp.push('周期购规格')
          }
          if (Array.isArray(estimeDeliverList)) {
            this.estimeDeliverStr = ''
            this.formData.item_cycle_delivery
            estimeDeliverList.forEach(item => {
              if (item.active) {
                this.formData.item_cycle_delivery = item.estime_deliver // 配送时间要提交的数据
                this.estimeDeliverStr = `(首次送达预计于 ${item.estime_deliver})`
                estimeDeliverArr.push(item.cycle_send_time)
                propName.push('配送时间')
              }
            })
            if (estimeDeliverList.length > 0) noChooseProp.push('配送时间')
          }
        }
        /*eslint no-extend-native: ["error", { "exceptions": ["Array"] }]*/
        Array.prototype.remove = function(val) {
          var index = this.indexOf(val)
          if (index > -1) {
            this.splice(index, 1)
          }
        }
        propName.forEach(item => {
          noChooseProp.remove(item)
        })
        // 赋值筛选未选择的部分
        this.noChooseProp = noChooseProp
        if (noChooseProp.length > 0) {
          const skuNameTemp=noChooseProp.join(' ') || '商品规格'
          this.skuNameStr = `选择：${skuNameTemp} `
        } else {
          this.skuNameStr = `已选 ${arrSkuName.join(' ')} ${buySpecArr.join(' ')} ${estimeDeliverArr.join(' ')}`
        }
      },
      /**
       * 立即购买
       */
      handleClickBuyNow() {
        const formData = this.formData
        const orderBuy = {}
        const obj = {}
        obj.item_id = this.itemId
        if (this.htmlData.activity == 6 && this.htmlData.is_item_detail_style == '0' && this.dhSkuList.length > 0) { // 订货模式
          const arrId = []
          const arrNum = []
          const dhSkuList = this.dhSkuList
          dhSkuList.forEach(item => {
            if (item.chooseNum > 0) {
              arrId.push(item.sku_id)
              arrNum.push(item.chooseNum)
            }
          })
          obj.value = arrId.join(',')
          obj.num = arrNum.join(',')
          orderBuy.sku = obj.value
          orderBuy.is_dhs_order = 'dhs_order'
          if (!obj.num) {
            this.$Error('购买的商品数量不能小于1')
            return false
          }
        } else if (this.htmlData.activity == 7) { // 周期购
          obj.num = formData.addNum
          orderBuy.sku = formData.skuKeyStr
          orderBuy.item_cycle_sku = formData.item_cycle_sku
          orderBuy.item_cycle_delivery = formData.item_cycle_delivery
          if (this.skuList.length > 0) { // sku未选择则提示
            if (this.noChooseProp.length > 0) {
              this.$Error(`${this.skuNameStr}`)
              return false
            }
          }
        } else { // 普通购物模式
          obj.sku = formData.skuKeyStr
          obj.num = formData.addNum
          orderBuy.sku = obj.sku
          // // console.log(obj, '普通模式')
          if (this.skuList.length > 0) { // sku未选择则提示
            if (this.noChooseProp.length > 0) {
              this.$Error(`${this.skuNameStr}`)
              return false
            }
          }
        }
        // 时间验证
        if (this.htmlData.item_config && this.htmlData.item_config.shopping_need_date == 1) {
          if (!formData.dateTime) {
            this.$Error(`请选择${this.htmlData.item_config.shopping_date_name}`)
            return false
          }
        }
        // 备注验证
        if (this.htmlData.item_config && this.htmlData.item_config.shopping_need_memo == 1) {
          if (!formData.mark) {
            this.$Error(`请填写备注`)
            return false
          }
        }
        // 跳转到结算
        orderBuy.point_exchange_id = this.htmlData.item_detail.point_exchange_id
        orderBuy.num = obj.num
        orderBuy.buy_type = 'onbuy'
        // 直播来源
        if (this.$route.query.source) {
          orderBuy.order_source = this.$route.query.source
        }
        if (this.$route.query.live_id) {
          orderBuy.live_id = this.$route.query.live_id
        }
        Store.save('pointBuy', orderBuy)
          window.open('/pointBuy')
      },
      /**
       * 加入购物车
       */
      handleClickAddCar() {
        const formData = this.formData
        const obj = {}
        obj.item_id = this.itemId
        if (this.htmlData.activity == 6 && this.htmlData.is_item_detail_style == '0' && this.dhSkuList.length > 0) { // 订货模式
          const dhSkuList = this.dhSkuList
          const data = []
          dhSkuList.forEach(item => {
            if (item.chooseNum > 0) {
              const temp = {
                item_id: this.itemId,
                sku_id: item.sku_id,
                num: item.chooseNum,
                supplier_id: this.htmlData.supplier_id
              }
              data.push(temp)
            }
          })
          obj.data = data
          obj.dhs_send = 1
          if (data.length < 1) {
            this.$Error('购买的商品数量不能小于1')
            return false
          }
        } else { // 普通购物模式
          obj.dhs_send = 0
          obj.sku_id = formData.skuKeyStr
          obj.num = formData.addNum
          if (this.skuList.length > 0) { // sku未选择则提示
            if (this.noChooseProp.length > 0) {
              this.$Error(`${this.skuNameStr}`)
              return false
            }
          }
        }
        // 时间验证
        if (this.htmlData.item_config && this.htmlData.item_config.shopping_need_date == 1) {
          if (!formData.dateTime) {
            this.$Error(`请选择${this.htmlData.item_config.shopping_date_name}`)
            return false
          }
        }
        // 备注验证
        if (this.htmlData.item_config && this.htmlData.item_config.shopping_need_memo == 1) {
          if (!formData.mark) {
            this.$Error(`请填写备注`)
            return false
          }
        }

        obj.item_date = formData.dateTime
        obj.item_memo = formData.mark
        obj.supplier_id = ''
        obj.point_exchange_id = this.htmlData.item_detail.point_exchange_id
        this.$loadingWrap.show()
        inPointCart(obj).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.$Error('已加入购物车')
            this.$Bus.$emit('changeCartNum', res.add_num)
            setTimeout(() => {
              this.overlayVisible = false
            }, 800)
          } else {
            this.$Error('添加失败：' + res.msg)
          }
        })
      },
      /**
       * 商品价格 整数放大
       */
      scaleGoodsPriceFn(price, className) {
        return scaleGoodsPrice(price, className)
      },

      // 日期转换
      formatDate(str) {
        let date = ''
        if (str) {
          const arr = str.split('-')
          date = new Date(arr[0], arr[1] - 1, arr[2]).toString()
        }
        return date
      },
      /**
       * 关闭弹窗
       */
      handleCloseDialog() {
        this.overlayVisible = false
        this.$emit('update:visible', false)
      },
      /**
       * 清空数据
       */
      clearData() {
        this.selectArr = [] // 存放被选中的值
        this.shopItemInfo = {} // 存放要和选中的值进行匹配的数据
        this.subIndex = [] // 是否选中因为不确定是多规格还是单规格，所以这里定义数组来判断
        this.skuList = []
        this.dhSkuList = []
        this.skuInfo = null
        this.skuObj = {}
        this.skuNameStr = ''
        this.htmlData = ''
        this.skuList = []
        this.buySpecList = []
        this.formData = {
          dateTime: '',
          addNum: 1,
          skuKeyStr: '',
          mark: '',
          item_cycle_sku: '',
          item_cycle_delivery: ''
        }
      },
      /**
       * 打开时间选择
       */
      handleOpenDatePicker() {
        this.dateTimeVisible = true
      },
      /**
       * 弹窗中的输入框失去焦点时页面复原
       */
      blurEvent() {
        window.scroll(0, 0)
      },
      /**
       * 获取详情
       */
      getDetailAjaxFn(val) {
        this.showSkuDetail = true
        this.htmlData = this.detailAll
        this.goodsImg = this.detailAll.item_detail.img_path[0]
        this.skuList = this.detailAll.item_detail.property_names || []
        if(this.skuList.length<=0){
          this.hasSku=false
        }
        const dhSkulist = this.detailAll.sku.arr_sku
        if (Array.isArray(dhSkulist)) {
          dhSkulist.forEach(item => {
            item.chooseNum = 0
          })
          this.dhSkuList = dhSkulist
        }
        if (this.detailAll.sku.sku) this.skuInfo = JSON.parse(this.detailAll.sku.sku)
        // 周期购规格
        this.validateSpecAll()
        // 处理是否有库存为0的sku
        this.initSku()
      }
    }
  })
</script>

<style  lang="scss">
  @import "src/styles/mixin";
  @import "src/styles/variables";
  .sku-pop{
    height:960px;
    border-radius:20px 20px 0 0;
    .sku-wrapper{
      height: 100%;
      position: relative;
      &-app{
        width: 100%;
        z-index: 10;
        background: #fff;
        &-head{
          display:flex;
          padding: 30px;
          font-size: 0;
          .left-wrap{
            .img{
              width: 186px;
              height: 186px;
              border-radius: 10px;
              background:#F5F5F5;
              overflow: hidden;
              img{
                width: 100%;
              }
            }
          }
          .right-wrap{
            flex:1;
            display:flex;
            flex-direction: column;
            justify-content: center;
            font-size: 22px;
            margin-left: 30px;
            &-item{
              margin-top:15px;
              color: #666;
              &.price{
                font-size: 32px;
                color: $priceColor;
              }
              .sku-dollar{
                color:#FFA101;
              }
            }
          }
          .close{
            width: 80px;
            height: 80px;
            line-height: 80px;
            position: absolute;
            color: #666;
            font-size: 46px;
            text-align: center;
            right: 0;
            top: 0;
            .icon-close{
              font-size:32px;
              color:#999;
            }
            .img-close{
              display: inline-block;
              width: 28px;
              height: 28px;
              background: url(https://img.wifenxiao.com/h5-wfx/images/common/close-icon.png) no-repeat center;
              background-size: 100% 100%;
            }
          }
        }
        &-body{
          // height: calc(100% - 300px);
          height:590px;
          min-height:590px;
          overflow: auto;
          padding:0 30px;
          -webkit-overflow-scrolling: touch;
          .sku-item{
            &-title{
              padding: 10px 0 24px;
              font-size: 26px;
              color: #333;
              .tips{
                font-size: 24px;
                color: #B7B7B7;
              }
            }
            &-app{
              padding:2px 0 10px;
              .btn{
                min-width:120px;
                height: auto;
                padding:10px 24px;
                margin-right: 24px;
                margin-bottom: 24px;
                font-size:22px;
                text-align: left;
                border-radius: 40px;
                @include btnGroup($fontSkuColor, $bgSkuColor);
                border-color: $bdSkuColor;
                &:last-child{
                  margin-right:0;
                }
                &.active{
                  @include btnGroup($fontCurSkuColor, $bgCurSkuColor);
                  border-color: $bdCurSkuColor;
                }
                &.noneActive{
                  background-color: #ccc;
                  opacity: 0.4;
                  color: #000;
                  pointer-events: none;
                }
              }
            }
            &-add, &-date{
              padding: 30px 0;
              &-title{
                font-size: 26px;
                color: #333;
                height: 60px;
                line-height: 60px;
              }
              &-con{
                display: inline-block;
                float: right;
                margin-top: 10px;
                .sku-bz-wd {
                  width: 410px;
                  input {
                    width: 100%;
                  }
                }
                .input{
                  font-size: 26px;
                  input{
                    text-align: center;
                    border: none;
                    color:#333;
                  }
                }
              }
            }
          }
        }
        &-foot{
          width: 100%;
          position: absolute;
          bottom: 0;
          left: 0;
          .sku-btn{
            display: flex;
            flex-direction: row;
            padding: 10px 24px;
            border-top:2px solid #EDEDED;
            &-item{
              flex: 1;
              width: 50%;
              font-size: 28px;
              text-align: center;
              height: 76px;
              line-height: 76px;
              color: #fff;
              &:first-child{
                border-radius: 40px 0 0 40px;
              }
              &:last-child{
                border-radius: 0 40px 40px 0;
              }
              &.pingt-gra-btn{
                border-radius: 40px;
                background: linear-gradient(to right, #FE1B49, #E90104);
              }
            }
          }
        }
      }
    }
  }
</style>
